<template>
  <div class="c-page-result-content">
    <ContentPageHeader title="STEP 03：核算结果解释" descText="请关注核算提示">
      <template #headerRight>
        <p class="title-des">最近核算于 {{ resultDetail.accountTime }}</p>
        <el-button @click="goDqr" v-if="dqrInfo?.dqr">
          <CIcon class="g-mr4" type="c-xian-shujuzhiliangfenxi"></CIcon>
          数据质量评价</el-button
        >
        <el-button
          @click="handleAnalysis"
          v-if="!resultDetail?.accountChangeFlag && accountStatus == 'ACCOUNTED'"
        >
          <CIcon class="g-mr4" type="c-xian-gengduofenxi"></CIcon>更多分析</el-button
        >
      </template>
    </ContentPageHeader>

    <div class="c-page-layout__body__content" v-if="accountStatus !== AccountTypeEnum.RUNNING">
      <CAlert
        style="margin-bottom: 16px"
        v-if="resultDetail?.accountChangeFlag"
        subtitle="本模型数据有更新，您可点击右上方【重新核算】获取最新核算结果"
        type="warning"
        close
      ></CAlert>
      <el-row :gutter="16">
        <el-col :span="8">
          <CStatisticItem
            class="out-wrap"
            :imgIcon="accountStatus == 'ACCOUNTED' ? 'icon_total' : 'icon_total_waring'"
            title="产品碳足迹总量"
            :subtitle="renderResultUnit(resultDetail.accountResult)"
          >
            <template #tag v-if="accountStatus == AccountTypeEnum.PART_ACCOUNTED">
              <div class="part-account-tag">部分核算</div>
            </template>
          </CStatisticItem>
        </el-col>
        <el-col :span="8">
          <CStatisticItem
            class="out-wrap"
            :imgIcon="accountStatus == 'ACCOUNTED' ? 'icon_unit' : 'icon_unit_waring'"
            title="单位产品碳足迹"
            :subtitle="`${renderResultUnit(resultDetail.unitResult)}/${
              resultDetail.referenceFlowUnit || ''
            }`"
          >
            <template #tag v-if="accountStatus == AccountTypeEnum.PART_ACCOUNTED">
              <div class="part-account-tag"> 部分核算 </div>
            </template>
            <template
              #rightTitle
              v-if="!!(resultDetail?.carType && accountStatus === AccountTypeEnum.ACCOUNTED)"
            >
              <div class="statistic-right">
                <span class="right-title__text">C-GCAP</span>
                <CIcon
                  class="right-title__icon"
                  type="c-xian-shuoming"
                  @click="handleShowCGCAP"
                ></CIcon>
                <p class="statistic-right__value">{{ empty(resultDetail?.score) }}</p>
              </div>
            </template>
          </CStatisticItem>
          <CGCAPDrawer v-model:visible="cgcapVisible" :carType="resultDetail?.carType ?? null" />
        </el-col>
        <el-col :span="8">
          <CStatisticItem
            class="out-wrap"
            :imgIcon="accountStatus == AccountTypeEnum.ACCOUNTED ? 'icon_dqr' : 'icon_dqr_waring'"
            :tips="dqrInfo.dqr ? '按95%置信区间计算' : '数据质量评分规则'"
            :title="dqrInfo.dqr ? '不确定度' : '数据质量分析'"
            :subtitle="renderResultUnit(resultDetail.accountResult)"
            @tipClick="seeRule(!dqrInfo.dqr)"
          >
            <template #desc>
              <p
                class="percent__value"
                v-if="accountStatus == AccountTypeEnum.ACCOUNTED && dqrInfo?.dqr"
                >{{ rateFormat(dqrInfo.uncertainty) }}
              </p>
              <p
                class="statistic-desc"
                v-else-if="
                  accountStatus == AccountTypeEnum.ACCOUNTED && !resultDetail?.accountChangeFlag
                "
                >数据偏差范围、DQR等， <span class="click-point" @click="goDqr">前往分析</span></p
              >
              <p class="statistic-desc" v-else>需先完成碳足迹完整核算</p>
            </template>
            <template
              #rightTitle
              v-if="
                accountStatus == AccountTypeEnum.ACCOUNTED &&
                !resultDetail?.accountChangeFlag &&
                dqrInfo.dqr
              "
            >
              <div class="statistic-right" style="width: 186px">
                <span class="right-title__text">DQR分值</span>
                <el-tooltip content="数据质量评分规则">
                  <CIcon
                    class="right-title__icon"
                    type="c-xian-shuoming"
                    @click="seeRule(true)"
                  ></CIcon>
                </el-tooltip>
                <div class="g-flex-start-center">
                  <span class="statistic-right__value g-mr6">{{ dqrInfo.dqr }}</span>
                  <CScopeTag type="text" :scope="dqrInfo.dqr"></CScopeTag>
                </div>
              </div>
            </template>
          </CStatisticItem>
        </el-col>
      </el-row>
      <div class="title-wrap g-flex--column g-mt16" :class="renderClass()">
        <div class="title-border"></div>
        <div class="g-flex-start-center">
          <p class="title">生命周期阶段分布</p>
          <el-divider class="title-divider" direction="vertical"></el-divider>
          <span class="title-tips"
            >BOM累加重量：{{ renderResultUnit(resultDetail?.productTotalDosage, '') }}</span
          >
        </div>
      </div>
      <CTable :data-source="stageListDataSource" useDataSource :pagination="false" :border="true">
        <vxe-column
          :title="`${ProcessStageMap[item.stage]}（CO₂e）`"
          v-for="item in stageList"
          :key="item.stage"
        >
          <template #default>
            <CTableColumn
              :main-text="
                isNullOrUnDef(item.accountResult)
                  ? '-'
                  : parseFloat((item.accountResult || 0).toFixed(3)) + ' kg'
              "
              :sub-text="`占比${rateFormat(item.accountRatio)}`"
            ></CTableColumn>
          </template>
        </vxe-column>
      </CTable>
    </div>
  </div>
  <div
    class="c-page-result-content g-mt16"
    v-if="accountStatus !== AccountTypeEnum.RUNNING && validList.length !== 0"
  >
    <div class="c-page-layout__body__title">
      <div class="g-flex-start-center">
        <span class="body-title__text">核算提示</span>
        <div class="short-line"></div>
        <span class="title-des">支持部分核算，以下结果仅做提示作用</span>
      </div>
    </div>
    <div class="gray_line"> </div>
    <div class="table-wrap">
      <CTable :data-source="validList" useDataSource :pagination="false">
        <vxe-column title="验证结果" width="150">
          <template #default="scope">
            <el-tag :type="renderColor(scope.row)"> {{ renderTag(scope.row) }}</el-tag>
          </template>
        </vxe-column>
        <vxe-column title="验证规则" minWidth="500">
          <template #default="scope">
            <CTableColumn
              :main-text="scope.row.ruleName"
              :sub-text="scope.row.ruleDesc"
            ></CTableColumn>
          </template>
        </vxe-column>
        <vxe-column title="备注" minWidth="500">
          <template #default="scope">
            <span>{{ empty(scope.row.remark) }}</span>
          </template>
        </vxe-column>
      </CTable>
    </div>
  </div>
  <div class="nodata" v-if="accountStatus == AccountTypeEnum.RUNNING">
    <div v-loading="true">
      <img class="img" src="@/assets/images/nodata_loading.png" />
    </div>
    <p class="g-font-14n3">核算结果生成中，请稍后…</p>
  </div>
  <DqrDrawer v-model:visible="dqrVisible"></DqrDrawer>
</template>

<script lang="ts" setup name="StepThree">
import { inject, defineExpose, ref } from 'vue';
import { CAlert } from '@/components/CAlert';
import { CStatisticItem } from '@/components/CStatisticItem';
import { CTable } from '@/components/CTable/index';
import { CTableColumn } from '@/components/CTable';
import { isNullOrUnDef } from '@/utils/is';
import ContentPageHeader from '../ContentPageHeader/index.vue';
import DqrDrawer from '../../../dqr/components/DqrDrawer/index.vue';

import { empty, rateFormat, renderResultUnit } from '@/utils';
import { MODEL_DETAIL_ROOT } from '../../types';
import type { ModelDetailRootProvider } from '../../types';
import { useCalc } from './useCalc';
import { ProcessStageMap, AccountTypeEnum } from '@/constants/enum';
// import { isBuildingMsg } from '@/utils/is';
import { useRouter } from 'vue-router';
import CGCAPDrawer from './components/CGCAPDrawer/index.vue';
import CScopeTag from '@/businessComponents/CScopeTag/index.vue';

const { modelNo } = inject(MODEL_DETAIL_ROOT) as ModelDetailRootProvider;
const {
  handleCalc,
  validList,
  stageList,
  resultDetail,
  accountStatus,
  stageListDataSource,
  dqrInfo
} = useCalc(modelNo);
const router = useRouter();

const renderColor = (item: any) => {
  // NEED_VALID("需验证"), REFERENCE("仅参考"), RUNNING("执行中"), SUCCESS("成功"), FAIL("失败"), WARNING("警告"),
  switch (item.ruleValidStatus) {
    case 'SUCCESS':
      return 'success';
    case 'FAIL':
      return 'danger';
    case 'WARNING':
    case 'RUNNING':
      return 'warning';
    default:
      return 'info';
  }
};
const renderTag = (item: any) => {
  switch (item.ruleValidStatus) {
    case 'SUCCESS':
      return '验证通过';
    case 'FAIL':
      return '验证失败';
    case 'WARNING':
      return '验证警示';
    case 'RUNNING':
      return '验证警示';
    case 'REFERENCE':
      return '验证中';
    default:
      return '需验证';
  }
};

const renderClass = () => {
  switch (accountStatus.value) {
    case AccountTypeEnum.ACCOUNTED:
      return 'title-wrap-success';
    case AccountTypeEnum.FAIL:
    case AccountTypeEnum.PART_ACCOUNTED:
      return 'title-wrap-waring';
    default:
      return '';
  }
};
// const handleEvaluation = () => {
//   isBuildingMsg();
// };
const handleAnalysis = () => {
  // router.push(`/pcfForm/emissionDistribution?modelNo=${resultDetail.value.modelNo}`);
  router.push(`/productCarbon/emissionDistribution?modelNo=${resultDetail.value.modelNo}`);
};

const cgcapVisible = ref(false);
function handleShowCGCAP() {
  cgcapVisible.value = true;
}
const dqrVisible = ref(false);
/**
 * 查看规则
 */
const seeRule = (enabled: boolean) => {
  if (!enabled) return;
  dqrVisible.value = true;
};
const goDqr = () => {
  router.push(`/myModel/dqr/${modelNo}`);
};

defineExpose({
  handleCalc
});
</script>

<style lang="scss" scoped>
.c-page-layout__body__title {
  margin: 0 20px;
  width: calc(100% - 40px);
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f2f3f5;
  .body-title__text {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #0a1f33;
    line-height: 22px;
  }
  .body-title__tag {
    height: 20px;
    background: #fcf7e6;
    border-radius: 3px;
    padding: 0 6px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #d19808;
    line-height: 20px;
    text-align: center;
  }
}
.title-des {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #7a8a99;
  line-height: 20px;
  display: inline-block;
  margin-right: 12px;
}
.c-page-layout__body__content {
  padding: 16px 20px 20px;
}
.c-page-result-content {
  width: 100%;
  background-color: #fff;
  border-radius: 3px;
}
.nodata {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 460px;
  background: #ffffff;
  border-radius: 0 0 3px 3px;
  padding-top: 141px;
  .img {
    width: 181px;
    height: 111px;
    margin-bottom: 9px;
  }
}
.table-wrap {
  padding: 16px 20px 64px;
}
.short-line {
  width: 1px;
  height: 10px;
  background: #ebeff2;
  margin: 0 8px;
}
.out-wrap {
  background: #f3f7fb;
  border-radius: 6px;
  .percent__value {
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 20px;
    color: #0a1f33;
    line-height: 32px;
    text-align: left;
    font-style: normal;
  }
  .right-title__text {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #435970;
    line-height: 22px;
    text-align: left;
    font-style: normal;
  }
  .right-title__icon {
    margin-left: 4px;
    color: #96a7b3;
    cursor: pointer;
    &:hover {
      color: $themeColor;
    }
  }
}

.gray-line {
  width: 100%;
  height: 1px;
  background: #f2f3f5;
  margin-bottom: 16px;
}

.title-wrap {
  width: 100%;
  height: 48px;
  background: #ffffff;
  border-left: 1px solid #ebeff2;
  border-right: 1px solid #ebeff2;
  overflow: hidden;
  border-radius: 6px 6px 0 0;
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #0a1f33;
    line-height: 46px;
    padding-left: 16px;
  }
  .title-divider {
    height: 10px;
  }
  .title-tips {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #7a8a99;
    line-height: 20px;
  }
}

.title-wrap-waring {
  background: linear-gradient(180deg, #fffdf7 0%, #ffffff 100%);
  .title-border {
    border-top: 2px solid #e1b205;
    width: 100%;
    // height: 2px;
    // background: #e1b205;
    border-radius: 6px;
  }
}
.title-wrap-success {
  background: linear-gradient(180deg, #f3fffc 0%, #ffffff 100%);
  .title-border {
    border-top: 2px solid #03ac82;
    width: 100%;
    // height: 2px;
    // background: #03ac82;
    border-radius: 6px;
  }
}

.part-account-tag {
  width: 60px;
  height: 20px;
  background: #e1b205;
  border-radius: 3px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  line-height: 20px;
  text-align: center;
  position: absolute;
  right: 8px;
  top: 8px;
}

.statistic-right__value {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 20px;
  color: #0a1f33;
  line-height: 32px;
  text-align: left;
  font-style: normal;
}
.statistic-desc {
  font-weight: 400;
  font-size: 14px;
  color: #7a8a99;
  line-height: 22px;
  margin-top: 5px;
}
.click-point {
  font-size: 14px;
  color: #308bf2;
  line-height: 22px;
  cursor: pointer;
}

.statistic-right {
  position: absolute;
  right: 0;
  top: 0;
  padding: 14px 12px 12px;
  width: 125px;
  height: 80px;

  &::before {
    left: 0;
    content: '';
    position: absolute;
    width: 1px;
    height: 48px;
    background-color: #ebeff2;
  }
}
</style>
